/*******************************************************************************
 * Copyright (c) 2000, 2010 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.karelun.ideaboard.gef.ui.actions;

import org.eclipse.emf.common.command.Command;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.actions.ActionFactory;
import org.karelun.ideaboard.gef.internal.GEFMessages;

import com.ibm.icu.text.MessageFormat;

/**
 * An action to undo the last command.
 */
public class UndoAction extends EditAction {

	public UndoAction(IEditorPart editor) {
		super(editor);
	}

	public UndoAction(IWorkbenchPart part) {
		super(part);
	}
	
	@Override
	protected boolean canExecutable() {
		return getCommandStack().canUndo();
	}
	
	/**
	 * Initializes this action's text and images.
	 */
	protected void init() {
		setId(ActionFactory.UNDO.getId());
		setToolTipText(MessageFormat.format(GEFMessages.UndoAction_Tooltip,
				new Object[] { "" }).trim()); //$NON-NLS-1$
		setText(MessageFormat.format(GEFMessages.UndoAction_Label,
				new Object[] { "" }).trim() //$NON-NLS-1$
		);
	}

	/**
	 * Refreshes this action's text to use the last executed command's label.
	 */
	public void update() {
		Command undoCmd = getCommandStack().getUndoCommand();
		setToolTipText(MessageFormat.format(GEFMessages.UndoAction_Tooltip,
				new Object[] { getLabelForCommand(undoCmd) }).trim());
		setText(MessageFormat.format(GEFMessages.UndoAction_Label,
				new Object[] { getLabelForCommand(undoCmd) }).trim());
		super.update();
	}
	
	private String getLabelForCommand(Command command) {
		if (command == null)
			return "";//$NON-NLS-1$
		if (command.getLabel() == null)
			return "";//$NON-NLS-1$
		else
			return command.getLabel();
	}

	/**
	 * Undoes the last command.
	 */
	public void run() {
		getCommandStack().undo();
	}

}
